const express = require("express");
//引入连接池模块
const pool = require("../pool.js");
//创建路由器对象
const router = express.Router();

//使用用户名登录
router.post("/login1",(req,res)=>{
  let obj = req.body;
  let sql = `select * from mz_user where uname = ? and upwd = ?`;
  pool.query(sql,[obj.uname,obj.upwd],(err,result)=>{
    if (err) throw err;
    if(result.length>0){
      res.send("1");
    }else{
      let sql = `select * from mz_user where phone = ? and upwd = ?`;
      pool.query(sql,[obj.phone,obj.upwd],(err,result)=>{
        if (err) throw err;
        if(result.length>0){
          res.send("1");
        }else{
          res.send("0");
        }
      })
    }
  })
})
//使用手机号码登录
router.post("/login2",(req,res)=>{
  let obj = req.body;
  let sql = `select * from mz_user where phone = ?`;
  pool.query(sql,[obj.phone],(err,result)=>{
    if (err) throw err;
    if(result.length>0){
      res.send("1");
    }else{
      res.send("0");
    }
  })
})


//注册用户
router.post("/register",(req,res)=>{
  let obj = req.body;
  let sql = `insert into mz_user (phone,upwd) values(?,?) `;
  pool.query(sql,[obj.phone,obj.upwd],(err,result)=>{
    if(err) throw err;
    if(result.affectedRows>0){
      res.send("1");
    }else{
      res.send("0");
    }
  })
})
//判断用户名是否存在
router.get("/isexists",(req,res)=>{
  let obj = req.query;
  let sql = `select * from mz_user where phone = ?`;
  pool.query(sql,[obj.phone],(err,result)=>{
    if(err) throw err;
    if(result.length>0){
      res.send("1");
    }else{
      res.send("0");
    }
  })
})

//通过手机型号查询所有对应手机信息模块
router.get('/searchEdi/:type&:id', (req, res) => {
  let type = req.params.type;
  let family_id = req.params.id;
  let sql = `select * from mz_${type} where family_id=?`
  pool.query(sql, [family_id], (err, result) => {
      if (err) throw err;
      res.send(result);
  })
});

//查询图片模块
router.get('/searchPic/:type&:id', (req, res) => {
  let type = req.params.type;
  let family_id = req.params.id;
 
  let sql = `select * from mz_${type}_pic where family_id=?`
  pool.query(sql, [family_id], (err, result) => {
      if (err) throw err;
      res.send(result);
  })
});

// 加入购物车
//根据规格获取手机信息
router.get("/carSpec/:type&:id&:spec",(req,res)=>{
  let type = req.params.type;
  let family_id = req.params.id;
  let spec = req.params.spec;

  let sql = `select * from mz_${type} where family_id=?`
  pool.query(sql,[family_id],(err,result)=>{
    if (err) throw err
    res.send(result[spec])
  })
})
//根据颜色获取手机信息
router.get("/carColor/:type&:id&:color",(req,res)=>{
  let type = req.params.type;
  let family_id = req.params.id;
  let color = req.params.color;

  let sql = `select * from mz_${type}_pic where family_id=?`
  pool.query(sql,[family_id],(err,result)=>{
    if (err) throw err
    res.send(result[color])
  })
})


module.exports = router;